<?php


namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Models\Service;
use App\Models\User;
use Dingo\Api\Http\Request;

class ServiceController extends BaseController
{
    public $model = Service::class;

    public function index(Request $request) {
        $title = $request->input('title');
        $category = $request->input('category');
        $type = $request->input('type', 'all');
        $is_special = $request->input('is_special', -1);
        $order_by_key = $request->input('order_by_key', 'sort');
        $order_by_value = $request->input('order_by_value', 'desc');

        $fields = '*';
        $list = Service::select($fields)->title($title)
            ->when($category, function ($q) use($category){
                $q->where('category', $category);
            })
            ->when($is_special!= -1, function ($q) use($is_special){
                $q->where('is_special', $is_special);
            });

        if($type == 'star') {
            $this->validate($request, [
               'target_user_id' => 'required'
            ]);
            $user = User::find(\request('target_user_id'));
            $target_entity_ids = $user->star()->where('type', 3)->pluck('entity_id')->all();
            $list = $list->whereIn('id', $target_entity_ids);
        }

        $list = $list->onStatus(1)->orderBy($order_by_key, $order_by_value)->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));
        return $this->paginate($list);
    }

    public function info(Request $request) {
        $id = \request("id");
        if (!$id) {
            return $this->failed("参数ID不存在");
        }
        $user_id = $this->getUserId();
        $info = Service::userStar($user_id)
            ->find($id);
        if (!$info)
            return $this->failed('服务已被删除');

        return $this->success($info);
    }


    /**
     * 保存|修改
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request) {
        $input = $request->input();
        $input['type'] = 1;
        if ($input['service_id'] != -1) {
            $service = Service::find($input['service_id']);
            if (!$service)
                return $this->failed('service_id 对应数据不存在');
            $service->increment('appoint_num', 1);
            $input['type'] = $service->type;
        }
        $user = $this->getUser();
        $input['user_id'] = $this->getUserId();
        $input['order_sn'] = create_order_no('ap');
        $info = Service::create($input);
        $id = $info->id;

        $user->increment('appoint_count', 1);
        return $this->success($id);
    }



}

